package cn.javase.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class HttpHandler implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
    private final Socket socket;

    public HttpHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            int byteLength = inputStream.available();
            if (byteLength == 0) {
                responseClient(outputStream, HttpStatus.OK, ContentType.TEXT_PLAIN, "");
                return;
            }
            handleClientRequest(inputStream);
            responseClient(outputStream, HttpStatus.OK, ContentType.TEXT_HTML, "<h1>首页</h1>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取客户端请求
     * @param inputStream 输入流
     * @return 结果
     * @throws IOException 异常
     */
    private static String handleClientRequest(InputStream inputStream) throws IOException {
        int byteLength = inputStream.available();
        byte[] requestBuff = new byte[byteLength];
        int read = inputStream.read(requestBuff);
        String requestStr = new String(requestBuff);
        logger.info(requestStr);
        String string = requestStr.split(System.lineSeparator())[0];
        logger.info(string);
        return requestStr;
    }

    /**
     * 构建响应
     * @param outputStream 输出流
     * @param status 响应状态
     * @param contentType 内容类型
     * @param content 内容
     * @throws IOException 异常
     */
    private static void responseClient(
            OutputStream outputStream,
            HttpStatus status,
            ContentType contentType, String content
    ) throws IOException {
        String lineSeparator = System.lineSeparator();
        String res = "HTTP/1.1 " + status.getCode() + " " + status.getReasonPhrase() + lineSeparator +
                "Content-Type: " + contentType + "; charset=UTF-8" + lineSeparator +
                lineSeparator +
                content + lineSeparator;
        outputStream.write(res.getBytes());
        outputStream.flush();
        outputStream.close();
    }

}
